<?php

class SalesJournalController extends Controller
{	
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';
		
	/**
	 * @var string the form input mode
	 */
	public $inputMode= '';
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('myadmin','myview'),
				'roles'=>array('customer','member'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','create','update','view', 'formaddrow'),
				'roles'=>array('admin','accountant'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
	
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionMyView($id)
	{
		$model = SalesJournal::model()->find('id=:id AND accountReceivableGlId=:accountReceivableGlId', 
			array('id'=>$id, 'accountReceivableGlId' => Yii::app()->user->customerGlId));
		
		if($model===null)
			throw new CHttpException(403,'You are not authorized to perform this action.');
		
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model = new SalesJournal;
		$model->salesGlId = Gl::GL_ID_SALES;
		$model->voucherPrefix = SalesJournal::VOUCHER_PREFIX;
		$model->voucherPostfix = $this->getNextVoucherPostfix();
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['SalesJournal']))
		{
			$model->attributes=$_POST['SalesJournal'];
		
			// tabular form SalesJournalItem
			$totalAmount = 0;
			$modelSalesJournalItem = array();
			$isValidSalesJournalItem = false;
			if(isset($_POST['SalesJournalItem']))
			{
				$items = Yii::app()->request->getPost('SalesJournalItem');
				$isValidSalesJournalItem = true;
				foreach ($items as $i => $item) 
				{
					$modelSalesJournalItem[$i] = new SalesJournalItem();
					$modelSalesJournalItem[$i]->setAttributes($item);
					$totalAmount += $modelSalesJournalItem[$i]->amount;
					if($isValidSalesJournalItem && !$modelSalesJournalItem[$i]->validate())
					{
						$isValidSalesJournalItem = false;
					}
				}
			}
			
			if(count($modelSalesJournalItem) == 0)
			{
				$errorCount = count($model->getErrors());
				$model->addError($errorCount,'Sales Item misssing');
			}
			
			// finaly save 
			if($isValidSalesJournalItem) 
			{
				$transaction = Yii::app()->db->beginTransaction();
				
				try
				{
					// create gl transaction debit
					$glTransactionDebit = new GlTransaction();
					$glTransactionDebit->voucherPrefix = $model->voucherPrefix;
					$glTransactionDebit->voucherPostfix = $model->voucherPostfix;
					$glTransactionDebit->createDate = $model->createDate;
					$glTransactionDebit->glId = $model->accountReceivableGlId;
					$glTransactionDebit->isDebit = 1;
					$glTransactionDebit->amount = $totalAmount;
					$glTransactionDebit->narration = $model->narration;
					if(!$glTransactionDebit->save())
					{
						Yii::log('failed to save GL Transaction:'.var_export($glTransactionDebit->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
						throw new CException('Fail to save Debit Gl Transaction');
					}
					$model->accountReceivableGlTransactionId = $glTransactionDebit->id;
					
					// create gl transaction credit
					$glTransactionCredit = new GlTransaction();
					$glTransactionCredit->voucherPrefix = $model->voucherPrefix;
					$glTransactionCredit->voucherPostfix = $model->voucherPostfix;
					$glTransactionCredit->createDate = $model->createDate;
					$glTransactionCredit->glId = $model->salesGlId;
					$glTransactionCredit->isDebit = 0;
					$glTransactionCredit->amount = $totalAmount;
					$glTransactionCredit->narration = $model->narration;
					if(!$glTransactionCredit->save())
					{
						Yii::log('failed to save GL Transaction:'.var_export($glTransactionCredit->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
						throw new CException('Fail to save Credit Gl Transaction');
					}
					$model->salesGlTransactionId = $glTransactionCredit->id;
					
					// save sales journal 
					if(!$model->save())
					{	
						Yii::log('failed to save SalesJournal: '.var_export($model->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
						throw new CException('Fail to save Sales Journal');
					}
					
					// save sales journal items
					foreach($modelSalesJournalItem as $item) 
					{
						$item->salesJournalId = $model->id;
						if(!$item->save())
						{
							Yii::log('failed to save SalesJournalItem: '.var_export($item->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
							throw new CException('Fail to save Sales Items');
						}
					}
					
					$transaction->commit();
					$this->redirect(array('view','id'=>$model->id));
				} 
				catch (Exception $ex) 
				{
					$transaction->rollback();
					$errorCount = count($model->getErrors());
					$model->addError($errorCount,$ex->getMessage());
					
				}
			}
		}
		$this->render('create',array(
			'model'=>$model,
			'modelSalesJournalItem'=>$modelSalesJournalItem,
		));
	}
	
	/**
	 * creates a new model row for tabular form.
	 * will show tabular form with new row.
	 */
	public function actionFormAddRow()
	{
		if(Yii::app()->request->isAjaxRequest) {
			$items = Yii::app()->request->getPost('SalesJournal');
			
			$modelSalesJournal = array();
			
			if (is_array($items)) { 
				//creating existing model instances + setting attributes
				foreach ($items as $i => $item) {
					$modelSalesJournal[$i] = new SalesJournal();
					$modelSalesJournal[$i]->setAttributes($item);
				}
			}
            //creating an additional empty model instance
            $modelSalesJournal[] = new SalesJournal();
            
            echo $this->renderPartial('application.views.salesJournal/_tabularform_additional', array("modelSalesJournal" => $modelSalesJournal));
            exit;

        } else {
            throw new CHttpException(404, 'Unable to resolve the request');
        }
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$this->inputMode = 'edit';
		$model=$this->loadModel($id);

		if(isset($_POST['SalesJournal']))
		{
			$model->attributes=$_POST['SalesJournal'];
			
			// validate journal items
			$modelSalesJournalItemIds = array();
			$totalAmount = 0;
			$modelSalesJournalItem = array();
			$isValidSalesJournalItem = false;
			if(isset($_POST['SalesJournalItem']))
			{
				$items = Yii::app()->request->getPost('SalesJournalItem');
				$isValidSalesJournalItem = true;
				foreach ($items as $i => $item) 
				{
					$modelSalesJournalItem[$i] = new SalesJournalItem();
					$modelSalesJournalItem[$i]->setAttributes($item);
					$totalAmount += $modelSalesJournalItem[$i]->amount;
					
					if(!empty($modelSalesJournalItem[$i]->id))
						$modelSalesJournalItemIds[] = $modelSalesJournalItem[$i]->id;
					
					
					if($isValidSalesJournalItem && !$modelSalesJournalItem[$i]->validate())
					{
						$isValidSalesJournalItem = false;
					}
				}
			}
			
			// show journal item missing message 
			if(count($modelSalesJournalItem) == 0)
			{
				$errorCount = count($model->getErrors());
				$model->addError($errorCount,'Sales Item misssing');
			}
			
			// finaly save 
			if($isValidSalesJournalItem) 
			{
				$transaction = Yii::app()->db->beginTransaction();
				
				try
				{
					// create gl transaction debit
					$glTransactionDebit = GlTransaction::model()->findByPk($model->accountReceivableGlTransactionId);
					$glTransactionDebit->amount = $totalAmount;
					$glTransactionDebit->narration = $model->narration;
					$glTransactionDebit->glId = $model->accountReceivableGlId;
					if(!$glTransactionDebit->save())
					{
						Yii::log('failed to save GL Transaction:'.var_export($glTransactionDebit->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
						throw new CException('Fail to save Debit Gl Transaction');
					}
					
					// create gl transaction credit
					$glTransactionCredit = GlTransaction::model()->findByPk($model->salesGlTransactionId);
					$glTransactionCredit->amount = $totalAmount;
					$glTransactionCredit->narration = $model->narration;
					$glTransactionCredit->glId = $model->salesGlId;
					if(!$glTransactionCredit->save())
					{
						Yii::log('failed to save GL Transaction:'.var_export($glTransactionCredit->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
						throw new CException('Fail to save Credit Gl Transaction');
					}
					
					// save sales journal 
					if(!$model->save())
					{	
						Yii::log('failed to save SalesJournal: '.var_export($model->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
						throw new CException('Fail to save Sales Journal');
					}
					
					// remove user deleted journal items
					if(count($cashReceiptJournalItemIds) == 0)
					{
						Yii::app()->db->createCommand("delete from salesjournalitem where salesJournalId = $model->id" )->query();
					}
					else
					{
						Yii::app()->db->createCommand("delete from salesjournalitem where id NOT IN (".implode(',', $cashReceiptJournalItemIds).")" )->query();
					}
					
					// save sales journal items
					foreach($modelSalesJournalItem as $item) 
					{
						$item->salesJournalId = $model->id;
						if(!$item->save())
						{
							Yii::log('failed to save SalesJournalItem: '.var_export($item->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
							throw new CException('Fail to save Sales Items');
						}
					}
					
					$transaction->commit();
					$this->redirect(array('view','id'=>$model->id));
				} 
				catch (Exception $ex) 
				{
					$transaction->rollback();
					$errorCount = count($model->getErrors());
					$model->addError($errorCount,$ex->getMessage());
					
				}
			}
		}
		else
		{
			$modelSalesJournalItem = SalesJournalItem::model()->findAll(array(
				'condition'=>'salesJournalId=:salesJournalId',
				'params'=>array(':salesJournalId'=>$id),
			));
		}

		$this->render('update',array(
			'model'=>$model,
			'modelSalesJournalItem'=>$modelSalesJournalItem,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('SalesJournal');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new SalesJournal('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['SalesJournal']))
			$model->attributes=$_GET['SalesJournal'];
		
		$this->render('admin',array(
			'model'=>$model,
		));
	}
	
	/**
	 * Manages authenticated user models.
	 */
	public function actionMyAdmin()
	{
		
		$model=new SalesJournal('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['SalesJournal']))
			$model->attributes=$_GET['SalesJournal'];
		
		$model->accountReceivableGlId = Yii::app()->user->customerGlId;
		
		$this->render('myadmin',array(
			'model'=>$model,
			'customerGlId'=>Yii::app()->user->customerGlId,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=SalesJournal::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='sales-journal-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	/**
	 * generate next sales voucher number.
	 */
	protected function getNextVoucherPostfix()
	{
		$criteria=new CDbCriteria;
		$criteria->select='max(voucherPostfix) as voucherPostfix';
		$criteria->condition = 'voucherPrefix=:voucherPrefix';
		$criteria->params = array(':voucherPrefix'=>SalesJournal::VOUCHER_PREFIX);
		$maxPostfixRow = SalesJournal::model()->find($criteria);
		return $maxPostfixRow['voucherPostfix'] + 1;
	}
}
